package com.wb.utils

import com.wb.vo.qq_music.Midurlinfo
import com.wb.vo.qq_music.Song
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.apache.commons.lang3.RandomStringUtils
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

/**
 * 原神工具类
 *
 * @author 祁雪
 */
class QQMusicUtil {


    companion object {

        // 搜索音乐
        val SEARCH_URL = "https://c.y.qq.com/soso/fcgi-bin/client_search_cp";

        // 获取音乐播放链接
        val MUSIC_PLAY_URL = "https://u.y.qq.com/cgi-bin/musicu.fcg";

        // 获取专辑链接
        val ALBUM_URL = "http://imgcache.qq.com/music/photo/album_300/17/300_albumpic_%s_0.jpg";

        val header = hashMapOf(
            "user-agent" to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
            "content-type" to "application/json"
        )

        /**
         * 搜索音乐
         *
         * @param key 搜索词
         * @param pageNo 页码
         */
        fun searchMusic(
            key: String,
            pageNo: String
        ): ArrayList<Song> {
            var result = RestUtil.sendGet(
                SEARCH_URL, hashMapOf(
                    "format" to "json",
                    "w" to key,
                    "p" to pageNo,
                    "n" to "20",
                    "new_json" to "1",
                    "_" to System.currentTimeMillis().toString()
                )
            )

            val list = arrayListOf<Song>()

            val gson = Gson()

            var map = gson.fromJson(
                result,
                object : TypeToken<HashMap<String, Any>>() {}.type
            ) as HashMap<String, Any>

            if (map.containsKey("data")) {

                map = gson.fromJson(
                    gson.toJson(map.get("data")),
                    object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                if (map.containsKey("song")) {

                    map = gson.fromJson(
                        gson.toJson(map.get("song")),
                        object : TypeToken<HashMap<String, Any>>() {}.type
                    ) as HashMap<String, Any>

                    if (map.containsKey("list")) {
                        val songs = gson.fromJson(
                            gson.toJson(map.get("list")),
                            object : TypeToken<ArrayList<Song>>() {}.type
                        ) as ArrayList<Song>
                        return songs
                    }
                }
            }
            return list
        }


        /**
         * 获取音乐播放链接
         *
         * @param mid 音乐ID
         * @return k.音乐
         */
        fun getMusicPlayUrl(mid: String): ArrayList<String>? {

            val gson = Gson()
            val result = RestUtil.sendGet(
                MUSIC_PLAY_URL, hashMapOf(
                    "format" to "json",
                    "inCharset" to "utf8",
                    "outCharset" to "utf-8",
                    "data" to gson.toJson(
                        hashMapOf(
                            "req_0" to hashMapOf(
                                "module" to "vkey.GetVkeyServer",
                                "method" to "CgiGetVkey",
                                "param" to hashMapOf(
                                    "guid" to System.currentTimeMillis().toString(),
                                    "songmid" to arrayOf(mid),
                                    "songtype" to arrayOf(0),
                                    "uin" to "0",
                                    "loginflag" to 1,
                                    "platform" to "20"
                                )
                            )
                        )
                    )
                )
            )

            var map = gson.fromJson(
                result,
                object : TypeToken<HashMap<String, Any>>() {}.type
            ) as HashMap<String, Any>

            if (map.containsKey("req_0")) {

                map = gson.fromJson(
                    gson.toJson(map.get("req_0")),
                    object : TypeToken<HashMap<String, Any>>() {}.type
                ) as HashMap<String, Any>

                if (map.containsKey("data")) {

                    map = gson.fromJson(
                        gson.toJson(map.get("data")),
                        object : TypeToken<HashMap<String, Any>>() {}.type
                    ) as HashMap<String, Any>

                    var sips = arrayListOf<String>()

                    if (map.containsKey("sip")) {

                        sips = gson.fromJson(
                            gson.toJson(map.get("sip")),
                            object : TypeToken<ArrayList<String>>() {}.type
                        ) as ArrayList<String>
                        if (sips.size == 0) {
                            sips.add("http://ws.stream.qqmusic.qq.com/")
                        }
                    }

                    if (map.containsKey("midurlinfo")) {

                        val midurlinfos = gson.fromJson(
                            gson.toJson(map.get("midurlinfo")),
                            object : TypeToken<ArrayList<Midurlinfo>>() {}.type
                        ) as ArrayList<Midurlinfo>

                        val urls = arrayListOf<String>()

                        sips.forEach { it ->
                            midurlinfos.forEach { info ->
                                if (info.purl.isNullOrEmpty()) {
                                    return@forEach
                                }
                                urls.add("${it}${info.purl}")
                            }
                        }
                        return urls
                    }

                }

            }

            return null

        }

        // QQ音乐猫猫码拼接
        fun getCatCode(song: Song): String {
            val jusmpUrl = "https://y.qq.com/n/ryqq/songDetail/${song.mid}?songtype=0&ADTAG=h5_playsong"
            val picUrl = "http://imgcache.qq.com/music/photo/album_300/17/300_albumpic_${song.album?.id}_0.jpg"

            /**
             * [CAT:other,code=[mirai:origin:MUSIC_SHARE]]
             * [CAT:music,kind=QQ,musicUrl=音乐播放链接,
             * title=音乐名称,jumpUrl=分享落地页,
             * pictureUrl=专辑链接,summary=歌手名称,brief=[分享]音乐名称]
             */

            val urls = getMusicPlayUrl(song.mid!!)

            val singerStr = song.singer.map { it.name }.joinToString(separator = " ")
            val msg = "[CAT:other,code=[mirai:origin:MUSIC_SHARE]]" +
                    "[CAT:music,kind=QQ,musicUrl=${urls?.get(0)}," +
                    "title=${song.name},jumpUrl=${jusmpUrl}," +
                    "pictureUrl=${picUrl},summary=${singerStr},brief=分享 - ${song.name}]"

            return msg
        }
    }

}

fun main() {

    val songs = QQMusicUtil.searchMusic("习惯两个人", "1")

    println(songs.get(0).mid)
    QQMusicUtil.getMusicPlayUrl(songs.get(0).mid!!)!!.forEach {
        println("播放链接: ${it}")
    }

}